﻿using MediatR;
using PublicCommon;
using T_Rbac.Read.APi.Application.Command.Quanxian;
using T_Rbac_Demain;
using T_Rbac_Rep.Interface;

namespace T_Rbac.Read.APi.Application.Handlers.Quanxian
{
    public class QuanxianMenusHandlers : IRequestHandler<QuanxianFantianByidIncludeMpidCommand, List<PublicTree<Menues>>>
    {
        private readonly IMenues menues;
        private readonly IjobMenuesRep ijobMenuesRep;

        public QuanxianMenusHandlers(IMenues menues, IjobMenuesRep ijobMenuesRep)
        {
            this.menues = menues;
            this.ijobMenuesRep = ijobMenuesRep;
        }

        public async Task<List<PublicTree<Menues>>> Handle(QuanxianFantianByidIncludeMpidCommand request, CancellationToken cancellationToken)
        {
            var list = await ijobMenuesRep.GetvaluesByResult(x => x.IsDel == false && x.Jjid == request.id);
            var midints = list.Select(x => x.Mid).ToArray();
            var menueslist = await menues.GetvaluesByResult(x => midints.Contains(x.Mid));
            var treelists = new List<PublicTree<Menues>>();
            foreach (var item in menueslist.Where(x=>x.Mpid==0).ToArray())
            {
                var tree = new PublicTree<Menues>
                {
                    label = item.Mname,
                    route = item.Mroute,
                    level = item.Mid,
                    children = null
                };
                treelists.Add(tree);
                await Getchidren(menueslist.Where(x => x.Mpid == item.Mid).Select(x=>x.Mid).ToArray(), tree);
            }
            return await Task.FromResult(treelists);
        }
        public async Task Getchidren(int[] id, PublicTree<Menues> tree)
        {
            var list = await menues.GetvaluesByResult(x => id.Contains(x.Mid) && !x.IsDel);
            foreach (var item in list)
            {
                if (tree.children == null)
                {
                    tree.children = new List<PublicTree<Menues>>();
                }
                var substree = new PublicTree<Menues>
                {
                    label = item.Mname,
                    level = item.Mid,
                    route = item.Mroute,
                    children = null
                };
                tree.children.Add(substree);
             
            }
        }
    }
}
